package com.zzj.security.jwt.controller;

import com.zzj.security.jwt.entity.SysUser;
import com.zzj.security.jwt.entity.dto.HttpResult;
import com.zzj.security.jwt.service.SysUserService;
import com.zzj.security.jwt.utils.SecurityUtils;
import org.apache.catalina.security.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.security.RolesAllowed;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 *  当@EnableGlobalMethodSecurity(securedEnabled=true)的时候，@Secured @PreAuthorize @PostAuthorize 可以使用
 *  @Secured 匹配的字符串需要添加前缀“ROLE_“。 如 @Secured({"ROLE_normal","ROLE_admin"}) 拥有normal或者admin角色的用户都可以访问此注解的方法。
 *
 * @ClassName SysUserController
 * @Description TODO
 * @Author zhijun zeng at 23:17 2020/5/17
 * @Version 1.0
 **/
@RestController
@RequestMapping("/ajax/admin/sysUser")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    /**
     * @RolesAllowed 必须 要以 ROLE_ 开头  ROLE_角色名
     * @param authentication
     * @return
     */
    @RequestMapping(value = "/authRoles")
    @RolesAllowed({"ROLE_sysadmin","ROLE_admin"})
    public HttpResult findAuthenticatedRoles(Authentication authentication) {
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> rolestr = new ArrayList<>();
        authorities.forEach((auth) -> {
            rolestr.add(auth.getAuthority());

        });
        return HttpResult.success().add(rolestr);
    }

    @RequestMapping(value = "")
    //@PreAuthorize("hasAnyAuthority('sysadmin','admin')")
    public HttpResult findAll() {
        return HttpResult.success().add(sysUserService.findAll());
    }

    @RequestMapping(value = "/info")
    public HttpResult userInfo() {
        return HttpResult.success().add(sysUserService.findByUsername(SecurityUtils.getUsername()));
    }





}
